/**
* All Rights Reserved , Copyright (C) 2021 , 青岛鼎信通讯股份有限公司
*
* SdWfFormService
* SD项目审批流表
*
* 修改纪录
* 2021-11-30 版本：1.0 jiangtao 创建。
* @version 版本：1.0
* @author 作者：jiangtao
* 创建日期：2021-11-30
*/
package com.topscomm.gpm.service.impl;

import com.topscomm.base.service.impl.BaseChangeLogService;
import com.topscomm.basic.BasicService;
import com.topscomm.basic.exception.ServiceException;
import com.topscomm.cbo.pojo.CboApprovalNodeEntity;
import com.topscomm.cbo.pojo.CboApprovalNodeInsEntity;
import com.topscomm.mms.service.impl.MmsProvinceCityMatchinfoService;
import com.topscomm.pub.util.ConvertUtil;
import com.topscomm.pub.util.SpringUtil;
import com.topscomm.gpm.GpmSystemConst;
import com.topscomm.gpm.pojo.*;
import com.topscomm.tap.TapEntity;
import com.topscomm.tap.common.FlowDatacodeCache;
import com.topscomm.tap.common.SessionUserBean;
import com.topscomm.tap.common.TapSystemConst;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;

import com.topscomm.gpm.service.IGpmWfFormService;
import com.topscomm.gpm.service.impl.auto.GpmWfFormServiceAuto;
import com.topscomm.basic.BasicEntity;
import com.topscomm.basic.util.PrimaryKeyUtil;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

@Service(value = "gpmWfFormService")
@Scope(value = "singleton")
public class GpmWfFormService extends GpmWfFormServiceAuto implements IGpmWfFormService {
	@Autowired
	private MmsProvinceCityMatchinfoService mmsProvinceCityMatchinfoService;
	@Autowired
	private GpmProjectHistoryService gpmProjectHistoryService;
	@Autowired
	private BaseChangeLogService baseChangeLogService;
	@Autowired
	private GpmProjectUniversalChangeService gpmProjectUniversalChangeService;
	@Autowired
	private GpmProjectService gpmProjectService;
	/**
	 * @author: jiangtao
	 * @date: 2021-11-30
	 * @param entity
	 * @description:单号生成
	 * @modify:
	 */
	@Override
	protected void beforeInsert(BasicEntity entity){
		super.beforeInsert(entity);
		if (entity.getId() <= 0) {// 赋值Id和单号
			long[] arrayId = PrimaryKeyUtil.GeneIDs(entity.getTableName(), 1);
			entity.setId(arrayId[0]);
			String docNo = String.valueOf(arrayId[0]);
			docNo = docNo.substring(0, 6) + docNo.substring(9);
			entity.setValue(GpmWfFormEntity.FieldDocno, docNo);
		}
	}

	/***
	 * @description: SD审批流程实体生成
	 * @param sourcetype
	 * @param entity
	 * @param approvaltype
	 * @return
	 * @author: jiangtao1
	 * @date: 2021/11/30 9:23
	 * @modify:
	 */
	@Override
	public GpmWfFormEntity generateWfFormEntity(String sourcetype, BasicEntity entity, String approvaltype) {
		GpmWfFormEntity wfFormEntity = new GpmWfFormEntity();
		List<String> allowList = new ArrayList<>(Collections.singletonList(GpmProjectEntity.tableName));
		List<String> allowFinalList = new ArrayList<String>(Collections.singletonList(
                GpmProjectHistoryEntity.tableName
        ));
		if(allowList.contains(sourcetype)) {
			wfFormEntity.setVersion(ConvertUtil.convertToLong(entity.getValue("version")));
			wfFormEntity.setSourceid(ConvertUtil.convertToLong(entity.getValue("id")));
			wfFormEntity.setFinalsourceid(ConvertUtil.convertToLong(entity.getValue("id")));
			wfFormEntity.setFinalversion(wfFormEntity.getVersion());
			wfFormEntity.setFinalsourcetype(sourcetype);
		} else if (allowFinalList.contains(sourcetype)) {
			wfFormEntity.setVersion(ConvertUtil.convertToLong(entity.getValue("version")));
			wfFormEntity.setSourceid(ConvertUtil.convertToLong(entity.getValue("id")));
			if(GpmProjectHistoryEntity.tableName.equals(sourcetype)) {
				wfFormEntity.setFinalversion(ConvertUtil.convertToLong(entity.getValue("version")));
				wfFormEntity.setFinalsourceid(ConvertUtil.convertToLong(entity.getValue("projectid")));
				wfFormEntity.setFinalsourcetype(GpmProjectEntity.tableName);
			}
		} else {
			wfFormEntity.setFinalsourcetype(sourcetype);
		}
		String deptCommonCode = mmsProvinceCityMatchinfoService.getDeptCommonCode(getSessionUserBean().getDept().getCode());
		wfFormEntity.setDeptcommoncode1(deptCommonCode);
		wfFormEntity.setSourcetype(sourcetype);
		wfFormEntity.setUsercode(this.getSessionUserBean().getUser().getCode());
		wfFormEntity.setUsername(this.getSessionUserBean().getUser().getName());
		wfFormEntity.setOrgcode(this.getSessionUserBean().getOrg().getCode());
		wfFormEntity.setDeptcode(this.getSessionUserBean().getDept().getCode());
		wfFormEntity.setBusinesstype(approvaltype);
		wfFormEntity.setDocdate(new Date());
		wfFormEntity.setSubmitdate(new Date());
		// 生成单号
		long[] arrayId = PrimaryKeyUtil.GeneIDs(wfFormEntity.getTableName(), 1);
		wfFormEntity.setId(arrayId[0]);
		String docNo = String.valueOf(arrayId[0]);
		docNo = docNo.substring(0, 6) + docNo.substring(9);
		wfFormEntity.setDocno(docNo);
		return wfFormEntity;
	}

	/***
	 * @description: 审批流程选择
	 * @param flowtype
	 * @param businessCode
	 * @param sessionUserBean
	 * @return
	 * @author: jiangtao1
	 * @date: 2021/11/30 9:27
	 * @modify:
	 */
	public long queryFlowid(String flowtype, String businessCode, SessionUserBean sessionUserBean) {
		long flowid = 0L;
		FlowDatacodeCache flowDatacodeCache = (FlowDatacodeCache) SpringUtil.getBean("flowDatacodeCache");
		List<Map<String, Object>> flowidList = flowDatacodeCache.getApprovalFlowListMap(flowtype, sessionUserBean,
				"sortcode");
		for (int i = flowidList.size() - 1; i >= 0; i--) {
			String flowcode = ConvertUtil.convertToString(flowidList.get(i).get("code"));
			if (!businessCode.equals(flowcode)) {
				flowidList.remove(i);
			}
		}
		if (flowidList.size() > 0) {
			flowid = ConvertUtil.convertToLong(flowidList.get(0).get("id"));
		}
		return flowid;
	}

	@Override protected void afterApprove(TapEntity billEntity, CboApprovalNodeInsEntity nodeIns, CboApprovalNodeEntity node, SessionUserBean sessionUserBean) {
		GpmWfFormEntity wfFormEntity = (GpmWfFormEntity)billEntity;
		int state = wfFormEntity.getState();
		String businesstype = wfFormEntity.getBusinesstype();
		String sourcetype = wfFormEntity.getSourcetype();
		String sourceid = ConvertUtil.convertToString(wfFormEntity.getSourceid());
		// 如果审核不通过
		if(TapSystemConst.TapApprovalFlowStateEnum.Back == state) {
			// 如果是立项
			if(GpmSystemConst.SdApprovalCategory.SdProjectApproval.equals(businesstype)) {
				BasicService basicService = this.queryBaiscService(sourcetype);
				BasicEntity basicEntity = basicService.queryById(sourceid);
				basicEntity.setValue(GpmProjectEntity.FieldState,"2");
				basicEntity.setValue(GpmProjectEntity.FieldProjectstate, GpmSystemConst.SdProjectState.ProjectUnApprovaled);
				basicService.updateEntity(basicEntity);
			} else if (GpmSystemConst.SdApprovalCategory.SdProjectChange.equals(businesstype)) {
				BasicService basicService = this.queryBaiscService(sourcetype);
				BasicEntity basicEntity = basicService.queryById(sourceid);
				basicEntity.setValue(GpmProjectEntity.FieldState,"2");
				basicService.updateEntity(basicEntity);
			}
		}
		//变更审批更新通用变更表
		if (GpmSystemConst.SdApprovalCategory.SdProjectChange.equals(businesstype)) {
			//修改变更模块记录
			Map<String,Object> changeUpdateMap = new HashMap<String,Object>();
			changeUpdateMap.put(GpmProjectUniversalChangeEntity.FieldState, wfFormEntity.getState());
			changeUpdateMap.put(GpmProjectUniversalChangeEntity.FieldLatestphase, wfFormEntity.getLatestphase());
			gpmProjectUniversalChangeService.updateByWhere(changeUpdateMap,"sourceid="+wfFormEntity.getSourceid() + " and sourcetype='"+ GpmProjectHistoryEntity.tableName +"' and version="
					+wfFormEntity.getVersion());
		}
		gpmProjectService.afterDecisionApprove(billEntity, nodeIns, node, sessionUserBean);
		super.afterApprove(billEntity, nodeIns, node, sessionUserBean);
	}

	@Override
	protected void afterDelApprove(TapEntity entity, SessionUserBean sessionUserBean) {
		GpmWfFormEntity wfFormEntity = (GpmWfFormEntity)entity;
		String sourcetype = wfFormEntity.getSourcetype();
		String sourceid = ConvertUtil.convertToString(wfFormEntity.getSourceid());
		//更新history表
		Map<String, Object> updateMap = new HashMap<String, Object>();
		updateMap.put(GpmProjectHistoryEntity.FieldId, wfFormEntity.getSourceid());
		updateMap.put(GpmProjectHistoryEntity.FieldState, wfFormEntity.getState());
		gpmProjectHistoryService.update(updateMap);
		//删除wfform表数据
		this.deleteById(ConvertUtil.convertToString(wfFormEntity.getId()));
		super.afterDelApprove(entity, sessionUserBean);
	}

	/***
	 * @description: 查找对应Service类
	 * @param sourcetype
	 * @return
	 * @author: jiangtao1
	 * @date: 2021/9/8 15:00
	 * @modify:
	 */
	private BasicService queryBaiscService(String sourcetype) {
		sourcetype = Character.toLowerCase(sourcetype.charAt(0)) + sourcetype.substring(1);
		String serviceName = sourcetype + "Service";
		BasicService basicService = (BasicService) SpringUtil.getBean(serviceName);
		return basicService;
	}

	/**
	 * @description: 变更退回修改节点审批通过
	 * @param id
	 * @return
	 * @author: wangxinhua
	 * @date: 2021/12/13 14:39
	 * @modify:
	 */
	@Transactional(rollbackFor = Exception.class)
	public void changeEditNodePass(String id) {
		GpmProjectHistoryEntity gpmProjectHistoryEntity = gpmProjectHistoryService.queryById(id);
		//删除上次德basechangelog
		baseChangeLogService.deleteByWhere(" topsourcetype='"+ gpmProjectHistoryEntity.getTableName()+"'"
				+ " and topsourceid='"+ gpmProjectHistoryEntity.getId()+"'"
				+ " and version="+ gpmProjectHistoryEntity.getVersion());
		//存变更记录
		Map<String, Object> nowHistoryInfo = gpmProjectHistoryEntity.convertToMap();
		try {
			Map<String, Object> changeData = gpmProjectHistoryService.getBaseChangeEntity(nowHistoryInfo);
			gpmProjectHistoryService.saveBaseChangelog(changeData, true);
		}catch (Exception e) {
			throw new ServiceException("保存变更信息：" + e.getMessage());
		}
	}
}
